package cn.cs.service.impl;

import cn.cs.client.*;
import cn.cs.common.*;
import cn.cs.config.AlipayConfig;
import cn.cs.config.WXPayConfig;
import cn.cs.pojo.*;
import cn.cs.service.QgWxpayService;
import cn.cs.service.WithdrawalPayService;
import cn.cs.util.GetWxOrderno;
import cn.cs.util.RequestHandler;
import cn.cs.util.WXPayUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


@Service
public class WithdrawalPayServiceImpl implements WithdrawalPayService {

    private Logger logger = Logger.getLogger(WithdrawalPayServiceImpl.class);

    @Resource
    private DataSourceTransactionManager transactionManager;

    @Resource
    private AlipayConfig alipayConfig;
    @Resource
    private WXPayConfig wxPayConfig;

    @Resource
    private QgWxpayService qgWxpayService;

    @Resource
    private RestAppSettlementClient appSettlementClient;

    @Resource
    private AgentSettlementDetailedClient agentSettlementDetailedClient;

    @Resource
    private RestRepairOrderClient restRepairOrderClient;

    @Resource
    private AgentSettlementClient agentSettlementClient;

    @Resource
    private SetPolicyClient setPolicyClient;

    @Resource
    private AgentClient agentClient;

    @Resource
    private CsPersonClient csPersonClient;

    @Resource
    private CsProportionSettingClient csProportionSettingClient;

    @Resource
    private AgentCapitalPoolDetailsClient capitalPoolDetailsClient;

    @Resource
    private WithdrawalPayClient withdrawalPayClient;


    @Override
    public Map<String, String> handleWithdrawalRepairUser(String id) throws Exception {
        return appSettlementClient.getAppSettlementById(id);
    }

    @Override
    public Map<String, String> handleWithdrawalAgent(String id) throws Exception {
        return agentSettlementDetailedClient.getSettlementDetailedById(id);
    }

    @Override
    public Map<String, String> handleWithdrawalAgentShop(String id) throws Exception {
        return agentSettlementClient.getShopSettlementDetailedById(id);
    }

    @Override
    public Integer updateState(String id, String personId) throws Exception {
        agentSettlementClient.updateShopSettlementDetailedState(id, personId);
        appSettlementClient.updateAppSettlementState(id, personId);
        return agentSettlementDetailedClient.updateSettlementDetailedState(id, personId);
    }


    @Override
    public Integer updateOrderStateAAgent(String id) throws Exception {
        return restRepairOrderClient.updateOrderStateAAgent(id);
    }

    @Override
    public Integer updateOrderStateBAgent(String id) throws Exception {
        return restRepairOrderClient.updateOrderStateBAgent(id);
    }

    @Override
    public CsPerson findPersonByName(String username) throws Exception {
        return csPersonClient.findPersonByName(username);
    }

    @Override
    public Agent getAgentById(String id) throws Exception {
        return agentClient.getAgentById(id);
    }

    @Override
    public Map<String, Object> getSetPolicyByType(String type) throws Exception {
        return setPolicyClient.getSetPolicyByType(type);
    }

    @Override
    public CsProportionSetting getProportionSetting()throws Exception{
        return csProportionSettingClient.getCsProportionSettingById("1");
    }


    @Override
    public void dealerSettlement(List<Map<String, String>> list, SettlementDetailed settlementDetailed, CapitalPoolDetails capitalPoolDetails) throws Exception {
        agentSettlementDetailedClient.addSettlementDetailed(settlementDetailed);
        agentSettlementDetailedClient.insertRepairOrderList(list);
        capitalPoolDetailsClient.addCapitalPoolDetails(capitalPoolDetails);
    }

    public Page<Map<String,Object>> queryQgTradePageByMap(Map<String,Object> param, Integer pageNo, Integer pageSize)throws Exception{
        Integer total = withdrawalPayClient.getQgTradeCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Map<String,Object>> productTypeList = withdrawalPayClient.getQgTradeListByMapPage(param);
        page.setRows(productTypeList);
        return page;
    }

    /**
     * 经销商收益批量转账
     * @param ids
     * @param username
     * @return
     * @throws Exception
     */

    public Dto agentHhandleWithdrawalBatch(String ids, String username)throws Exception{

        CsPerson person = csPersonClient.findPersonByName(username);
        if(EmptyUtils.isNotEmpty(person.getId())) {

            Map<String, Object> policy = setPolicyClient.getSetPolicyByType("2");
            int polCycle = Integer.valueOf(policy.get("pol_date").toString());

            int newDate = Integer.valueOf(DateUtil.format(new Date(), "d"));
            System.out.println(newDate);
            if (polCycle == newDate) {
                String _ids[] = ids.split(",");
                int ii = _ids.length;
                int j = 0;
                for (String id : _ids) {
                    DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition();
                    //开启新事物
                    transDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    TransactionStatus transStatus = transactionManager.getTransaction(transDefinition);



                    Agent agent = agentClient.getAgentById(id);
                    String type = agent.getType();
                    String openId = agent.getOpenid();
                    String alipayUserid = agent.getAlipayUserid();

                    if("1".equals(type)){
                        alipayUserid = "00000000000";
                    }else{
                        openId = "00000000000";
                    }

                    if (EmptyUtils.isNotEmpty(openId) && EmptyUtils.isNotEmpty(alipayUserid)) {

                        String typeId = agent.getTypeId();
                        String invitationCode = agent.getInvitationCode();

                        Map<String, Object> param = new HashMap<>();
                        String cycle = DateUtil.format(new Date(), "yyyy-MM") + "-01 00:00:01";
                        param.put("cycle", cycle);
                        param.put("isAppset", "0");
                        param.put("parentInvitationCode", invitationCode);

                        List<Map<String, Object>> repairOrderList = new ArrayList<>();
                        Double total = 0.00;
                        if ("1".equals(typeId)) {
                            param.put("agentAId", id);
                            total = restRepairOrderClient.getAppOrderAgentAProfitAllNew(param);
                            repairOrderList = restRepairOrderClient.getAppOrderAgentAByMapNew(param);
                        } else {
                            param.put("agentBId", id);
                            total = restRepairOrderClient.getAppOrderAgentAProfitAllNew(param);
                            repairOrderList = restRepairOrderClient.getAppOrderAgentAByMapNew(param);
                        }
                        total = new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        if(total > 0){
                            SettlementDetailed settlementDetailed = new SettlementDetailed();
                            String detailedId = IdWorker.getId();
                            settlementDetailed.setId(detailedId);
                            settlementDetailed.setSetTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                            settlementDetailed.setSetState("0");
                            settlementDetailed.setOpenid(openId);
                            settlementDetailed.setAlipayUserid(alipayUserid);
                            settlementDetailed.setAgentId(id);
                            settlementDetailed.setSetMoney(String.valueOf(total));
                            settlementDetailed.setSetState("0");
                            settlementDetailed.setType(type);
                            settlementDetailed.setAccountPeriod(DateUtil.getLastMonth(1));

                            List<Map<String, String>> list = new ArrayList<>();
                            for (Map<String, Object> a : repairOrderList) {
                                Map<String, String> map1 = new HashMap<>();
                                map1.put("id", IdWorker.getId());
                                map1.put("set_id", id);
                                map1.put("rep_order_id", a.get("orderId").toString());
                                list.add(map1);

                                if ("1".equals(agent.getTypeId())) {
                                    int i = restRepairOrderClient.updateOrderStateAAgent(a.get("orderId").toString());
                                    logger.info("info---------------------------------------------------------AAAAAAA：" + i);
                                } else {
                                    int i = restRepairOrderClient.updateOrderStateBAgent(a.get("orderId").toString());
                                    logger.info("info---------------------------------------------------------BBBBBB：" + i);
                                }
                            }
                            CsProportionSetting setting = csProportionSettingClient.getCsProportionSettingById("1");
                            Double capital_pool = Double.valueOf(setting.getCapitalPool());
                            Double money = total;

                            CapitalPoolDetails capitalPoolDetails = new CapitalPoolDetails();
                            capitalPoolDetails.setTitle("资金池入账");
                            capitalPoolDetails.setContent("资金池入账");
                            capitalPoolDetails.setAgentId(settlementDetailed.getAgentId());
                            capitalPoolDetails.setType("1");
                            capitalPoolDetails.setMoney(new BigDecimal(money * capital_pool).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

                            settlementDetailed.setCapital_pool_money(capitalPoolDetails.getMoney().toString());

                            agentSettlementDetailedClient.addSettlementDetailed(settlementDetailed);
                            agentSettlementDetailedClient.insertRepairOrderList(list);
                            capitalPoolDetailsClient.addCapitalPoolDetails(capitalPoolDetails);



                            Double capital_pool_money = Double.valueOf(capitalPoolDetails.getMoney());
                            String money1 = String.valueOf(new BigDecimal(total - capital_pool_money).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

                            String transactionId = "";
                            if ("1".equals(type)) {//微信
                                Map<String, String> m = new HashMap<>();
                                m.put("openid", openId);
                                m.put("orderId", detailedId);
                                m.put("money", money1);
                                m.put("spbillCreateIp", "127.0.0.1");

                                //暂时屏蔽付款
                                Map<String, Object> responseMap = sendPay(m);
                                if (responseMap != null && responseMap.size() > 0) {
                                    if ("SUCCESS".equals(responseMap.get("result_code").toString())) {
                                        transactionId = responseMap.get("partner_trade_no").toString();
                                        qgWxpayService.insertTrade(detailedId, transactionId, id, money1, "0");
                                        System.out.println("调用成功");
                                        agentSettlementClient.updateShopSettlementDetailedState(detailedId, person.getId());
                                        appSettlementClient.updateAppSettlementState(detailedId, person.getId());
                                        agentSettlementDetailedClient.updateSettlementDetailedState(detailedId, person.getId());

                                        j++;
                                        transactionManager.commit(transStatus);


                                    } else {
                                        String err_code = responseMap.get("err_code").toString();
                                        String msg = "操作失败";
                                        switch (err_code) {
                                            case "AMOUNT_LIMIT":
                                                msg += ",金额超限!";
                                                break;
                                            case "NOTENOUGH":
                                                msg += ",您的付款帐号余额不足或资金未到账!";
                                                break;
                                            case "SYSTEMERROR":
                                                msg += ",系统繁忙，请稍后再试!";
                                                break;
                                            case "V2_ACCOUNT_SIMPLE_BAN":
                                                msg += ",用户微信支付账户未知名，无法付款!";
                                                break;
                                            case "SENDNUM_LIMIT":
                                                msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";
                                                break;
                                            case "MONEY_LIMIT":
                                                msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";
                                                break;
                                            case "FREQ_LIMIT":
                                                msg += ",超过频率限制，请稍后再试!";
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                }
                            } else {//支付宝
                                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayConfig.getTransferAppID(), alipayConfig.getTransferPrivateKey(), "json", "UTF-8", alipayConfig.getTransferAlipayPublicKey(), "RSA2");
                                AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
                                request.setBizContent("{" +
                                        "\"out_biz_no\":\"" + detailedId + "\"," +
                                        "\"payee_type\":\"ALIPAY_USERID\"," +
                                        "\"payee_account\":\"" + alipayUserid + "\"," +
                                        "\"amount\":\"" + money1 + "\"," +
                                        "  }");

                                //暂时屏蔽支付
                                AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
                                if (response.isSuccess()) {
                                    System.out.println("调用成功");
                                    logger.info("info---------------------------------------------------------支付宝支付成功response：" + JSON.toJSON(response));
                                    transactionId = response.getOrderId();

                                    agentSettlementClient.updateShopSettlementDetailedState(detailedId, person.getId());
                                    appSettlementClient.updateAppSettlementState(detailedId, person.getId());
                                    agentSettlementDetailedClient.updateSettlementDetailedState(detailedId, person.getId());

                                    qgWxpayService.insertTrade(detailedId, transactionId, id, money1, "0");

                                    j++;
                                    transactionManager.commit(transStatus);

                                } else {
                                    System.out.println("调用失败");
                                    System.out.println(JSON.toJSON(response));
                                    logger.info("info---------------------------------------------------------支付宝支付失败response：" + JSON.toJSON(response));
                                }

                            }
                        }
                    }
                }
                if(ii == j){
                    return DtoUtil.returnSuccess("操作成功", "");
                }
                return DtoUtil.returnFail("转账操作未全部成功，可单个转账查看失败原因", "");
            } else {
                return DtoUtil.returnFail("当前不是结算日，无法结算", "0001");
            }
        }
        return DtoUtil.returnFail("操作失败，操作人不存在", "004");
    }


    /**
     * 经销商收益转账
     * @param id
     * @param username
     * @return
     * @throws Exception
     */

    public Dto agentHhandleWithdrawal(String id, String username)throws Exception{

        CsPerson person = csPersonClient.findPersonByName(username);
        if(EmptyUtils.isNotEmpty(person.getId())) {

            Map<String, Object> policy = setPolicyClient.getSetPolicyByType("2");
            int polCycle = Integer.valueOf(policy.get("pol_date").toString());

            int newDate = Integer.valueOf(DateUtil.format(new Date(), "d"));
            System.out.println(newDate);
            if (polCycle == newDate) {
                DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition();
                //开启新事物
                transDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
                TransactionStatus transStatus = transactionManager.getTransaction(transDefinition);

                Agent agent = agentClient.getAgentById(id);
                String type = agent.getType();
                String openId = agent.getOpenid();
                String alipayUserid = agent.getAlipayUserid();
                String msg1 = "";
                if("1".equals(type)){
                    alipayUserid = "00000000000";
                    msg1 = "管理商未绑定微信，请先提醒绑定";
                }else{
                    openId = "00000000000";
                    msg1 = "管理商未绑定支付宝，请先提醒绑定";
                }
                if (EmptyUtils.isNotEmpty(openId) && EmptyUtils.isNotEmpty(alipayUserid)) {

                    String typeId = agent.getTypeId();
                    String invitationCode = agent.getInvitationCode();

                    Map<String, Object> param = new HashMap<>();
                    String cycle = DateUtil.format(new Date(), "yyyy-MM") + "-01 00:00:01";
                    param.put("cycle", cycle);
                    param.put("isAppset", "0");
                    param.put("parentInvitationCode", invitationCode);
                    List<Map<String, Object>> repairOrderList = new ArrayList<>();
                    Double total = 0.00;
                    if ("1".equals(typeId)) {
                        param.put("agentAId", id);
                        total = restRepairOrderClient.getAppOrderAgentAProfitAllNew(param);
                        repairOrderList = restRepairOrderClient.getAppOrderAgentAByMapNew(param);
                    } else {
                        param.put("agentBId", id);
                        total = restRepairOrderClient.getAppOrderAgentAProfitAllNew(param);
                        repairOrderList = restRepairOrderClient.getAppOrderAgentAByMapNew(param);
                    }
                    total = new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    if(total > 0){
                        SettlementDetailed settlementDetailed = new SettlementDetailed();
                        String detailedId = IdWorker.getId();
                        settlementDetailed.setId(detailedId);
                        settlementDetailed.setSetTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        settlementDetailed.setSetState("0");
                        settlementDetailed.setOpenid(openId);
                        settlementDetailed.setAlipayUserid(alipayUserid);
                        settlementDetailed.setAgentId(id);
                        settlementDetailed.setSetMoney(String.valueOf(total));
                        settlementDetailed.setSetState("0");
                        settlementDetailed.setType(type);
                        settlementDetailed.setAccountPeriod(DateUtil.getLastMonth(1));

                        List<Map<String, String>> list = new ArrayList<>();
                        for (Map<String, Object> a : repairOrderList) {
                            Map<String, String> map1 = new HashMap<>();
                            map1.put("id", IdWorker.getId());
                            map1.put("set_id", id);
                            map1.put("rep_order_id", a.get("orderId").toString());
                            list.add(map1);

                            if ("1".equals(agent.getTypeId())) {
                                int i = restRepairOrderClient.updateOrderStateAAgent(a.get("orderId").toString());
                                logger.info("info---------------------------------------------------------AAAAAAA：" + i);
                            } else {
                                int i = restRepairOrderClient.updateOrderStateBAgent(a.get("orderId").toString());
                                logger.info("info---------------------------------------------------------BBBBBB：" + i);
                            }
                        }
                        CsProportionSetting setting = csProportionSettingClient.getCsProportionSettingById("1");
                        Double capital_pool = Double.valueOf(setting.getCapitalPool());
                        Double money = total;

                        CapitalPoolDetails capitalPoolDetails = new CapitalPoolDetails();
                        capitalPoolDetails.setTitle("资金池入账");
                        capitalPoolDetails.setContent("资金池入账");
                        capitalPoolDetails.setAgentId(settlementDetailed.getAgentId());
                        capitalPoolDetails.setType("1");
                        capitalPoolDetails.setMoney(new BigDecimal(money * capital_pool).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

                        settlementDetailed.setCapital_pool_money(capitalPoolDetails.getMoney().toString());

                        agentSettlementDetailedClient.addSettlementDetailed(settlementDetailed);
                        agentSettlementDetailedClient.insertRepairOrderList(list);
                        capitalPoolDetailsClient.addCapitalPoolDetails(capitalPoolDetails);

                        Double capital_pool_money = Double.valueOf(capitalPoolDetails.getMoney());
                        String money1 = String.valueOf(new BigDecimal(total - capital_pool_money).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

                        String transactionId = "";
                        if ("1".equals(type)) {//微信
                            Map<String, String> m = new HashMap<>();
                            m.put("openid", openId);
                            m.put("orderId", detailedId);
                            m.put("money", money1);
                            m.put("spbillCreateIp", "127.0.0.1");

                            //暂时屏蔽付款
                            Map<String, Object> responseMap = sendPay(m);
                            if (responseMap != null && responseMap.size() > 0) {
                                if ("SUCCESS".equals(responseMap.get("result_code").toString())) {
                                    transactionId = responseMap.get("partner_trade_no").toString();
                                    qgWxpayService.insertTrade(detailedId, transactionId, id, money1, "0");
                                    System.out.println("调用成功");

                                    agentSettlementClient.updateShopSettlementDetailedState(detailedId, person.getId());
                                    appSettlementClient.updateAppSettlementState(detailedId, person.getId());
                                    agentSettlementDetailedClient.updateSettlementDetailedState(detailedId, person.getId());

                                    transactionManager.commit(transStatus);

                                    return DtoUtil.returnSuccess("操作成功","");
                                } else {

                                    transactionManager.rollback(transStatus);

                                    String err_code = responseMap.get("err_code").toString();
                                    String msg = "操作失败";
                                    switch (err_code) {
                                        case "AMOUNT_LIMIT":
                                            msg += ",金额超限!";
                                            break;
                                        case "NOTENOUGH":
                                            msg += ",您的付款帐号余额不足或资金未到账!";
                                            break;
                                        case "SYSTEMERROR":
                                            msg += ",系统繁忙，请稍后再试!";
                                            break;
                                        case "V2_ACCOUNT_SIMPLE_BAN":
                                            msg += ",用户微信支付账户未知名，无法付款!";
                                            break;
                                        case "SENDNUM_LIMIT":
                                            msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";
                                            break;
                                        case "MONEY_LIMIT":
                                            msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";
                                            break;
                                        case "FREQ_LIMIT":
                                            msg += ",超过频率限制，请稍后再试!";
                                            break;
                                        default:
                                            break;
                                    }
                                    return DtoUtil.returnFail(msg, err_code);
                                }
                            }
                            return DtoUtil.returnFail("操作失败，请重试","003");
                        } else {//支付宝
                            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayConfig.getTransferAppID(), alipayConfig.getTransferPrivateKey(), "json", "UTF-8", alipayConfig.getTransferAlipayPublicKey(), "RSA2");
                            AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
                            request.setBizContent("{" +
                                    "\"out_biz_no\":\"" + detailedId + "\"," +
                                    "\"payee_type\":\"ALIPAY_USERID\"," +
                                    "\"payee_account\":\"" + alipayUserid + "\"," +
                                    "\"amount\":\"" + money1 + "\"," +
                                    "  }");

                            //暂时屏蔽支付
                            AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
                            if (response.isSuccess()) {
                                System.out.println("调用成功");
                                logger.info("info---------------------------------------------------------支付宝支付成功response：" + JSON.toJSON(response));
                                transactionId = response.getOrderId();

                                agentSettlementClient.updateShopSettlementDetailedState(detailedId, person.getId());
                                appSettlementClient.updateAppSettlementState(detailedId, person.getId());
                                agentSettlementDetailedClient.updateSettlementDetailedState(detailedId, person.getId());

                                qgWxpayService.insertTrade(detailedId, transactionId, id, money1, "0");

                                transactionManager.commit(transStatus);
                                return DtoUtil.returnSuccess("操作成功","");
                            } else {
                                transactionManager.rollback(transStatus);
                                System.out.println("调用失败");
                                System.out.println(JSON.toJSON(response));
                                logger.info("info---------------------------------------------------------支付宝支付失败response：" + JSON.toJSON(response));
                                return DtoUtil.returnFail("操作失败," + response.getSubMsg(),response.getSubCode());
                            }

                        }
                    }
                    return DtoUtil.returnFail("当前无收益，无需转账", "0002");
                }
                return DtoUtil.returnFail(msg1, "0002");
            }
            return DtoUtil.returnFail("当前不是结算日，无法结算", "0001");
        }
        return DtoUtil.returnFail("操作失败，操作人不存在", "0004");
    }

    /**
     * 经销商提现
     * @param m
     * @return
     * @throws Exception
     */
    public Map<String, Object> sendPay(Map<String, String> m)throws Exception {

        String openId = m.get("openid");
        // 1 参数
        // 订单号
        String orderId = m.get("orderId");
        // 总金额以分为单位，不带小数点
        String totalFee = WXPayUtil.getMoney(m.get("money"));

        // 订单生成的机器 IP
        String spbill_create_ip = m.get("spbillCreateIp");

        // ---必须参数
        // 商户号
        String mch_id = wxPayConfig.getMchID();
        // 随机字符串
        String nonce_str = WXPayUtil.getNonceStr();


        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", wxPayConfig.getJxsAppId());
        packageParams.put("mchid", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("desc", "经销商商城收益");
        packageParams.put("partner_trade_no", orderId);
        // 这里写的金额为1 分到时修改
        packageParams.put("amount", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("check_name", "NO_CHECK");
        packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(wxPayConfig.getJxsAppId(), wxPayConfig.getJxsSecret(), wxPayConfig.getKey());

        String sign = reqHandler.createSign(packageParams);
        logger.info("第一次签名------------------------------" + sign);
        System.out.println("第一次签名------------------------------" + sign);
        String xml = "<xml>" + "<mch_appid>" + wxPayConfig.getJxsAppId() + "</mch_appid>" + "<mchid>"
                + mch_id + "</mchid>" + "<nonce_str>" + nonce_str
                + "</nonce_str>"
                + "<partner_trade_no>" + orderId + "</partner_trade_no>"
                + "<openid>" + openId + "</openid>"
                + "<check_name>NO_CHECK</check_name>"
                + "<amount>" + totalFee + "</amount>"
                + "<desc>经销商商城收益</desc>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";


        Map<String, Object> map = new GetWxOrderno().sendPost(createOrderURL, xml);
        logger.info("info---------------------------------------------------------获取到的预支付ID：" + map);
        System.out.println("获取到的预支付ID：" + map);

        return map;
    }

}
